﻿using System.Text;
using System.Text.Json;

namespace SocketGateway.Tool
{
    /// <summary>
    /// 工具类
    /// </summary>
    public class ToolHelper
    {
        /// <summary>
        /// 读取JSON文件
        /// </summary>
        public static T JsonToObj<T>(string path)
        {
            var content = string.Empty;
            try
            {
                using var sr = new StreamReader(path, options: new FileStreamOptions { Access = FileAccess.Read, Mode = FileMode.Open, Share = FileShare.ReadWrite });
                content = sr.ReadToEnd();
            }
            catch { }
            if (string.IsNullOrWhiteSpace(content))
                return default;
            try
            {
                return JsonSerializer.Deserialize<T>(content, new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip });
            }
            catch { return default; }
        }

        /// <summary>
        /// 保存对象JSON到文件
        /// </summary>
        public static void SaveJsonToFile<T>(string path, T obj)
        {
            try
            {
                var content = JsonSerializer.Serialize(obj, new JsonSerializerOptions { WriteIndented = true });
                using var sw = new StreamWriter(path, new FileStreamOptions { Access = FileAccess.Write, Share = FileShare.ReadWrite, Mode = FileMode.Create });
                sw.Write(content);
            }
            catch { }
        }

        /// <summary>
        /// 获取框架配置JSON数据
        /// </summary>
        public static string GetFrameConfigJson()
        {
            var path = Path.Combine(AppContext.BaseDirectory, "DataConfig", "frame.config.json");
            try
            {
                using var sr = new StreamReader(path, Encoding.UTF8);
                return sr.ReadToEnd();
            }
            catch { return string.Empty; }
        }
    }
}
